package com.example.demo.scheduledtask;

import cn.hutool.core.util.ObjectUtil;
import com.alibaba.fastjson.JSONObject;
import com.baomidou.dynamic.datasource.annotation.DS;
import com.example.demo.common.Constant;
import com.example.demo.config.ErpConfig;
import com.example.demo.mapper.PoMpsinfoMapper;
import com.example.demo.mapper.WmsPurchaseMapper;
import com.example.demo.utils.SoapXmlUtil;
import com.example.demo.vo.PurchaseBackPostVo;
import com.example.demo.vo.XmlResp;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.annotation.Async;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;

/**
 * @author : Zhang.yt
 * @date : 2024/7/29
 */
@Component
@Slf4j
@DS("wms")
public class PurchaseBackPost {
    @Resource
    private WmsPurchaseMapper wmsPurchaseMapper;

    @Autowired
    private SoapXmlUtil soapXmlUtil;

    @Autowired
    PoMpsinfoMapper poMpsinfoMapper;

    @Resource
    private ErpConfig erpConfig;
    /**
     * 采购仓退
     */
    @Scheduled(fixedDelay = 30 * 1000)//开启定时同步
    //@Async(value = "taskExecutor")
    public void PurchaseBackPost() {
        PurchaseBackPostVo purchaseBackPost = wmsPurchaseMapper.getPurchaseBackPost();
        if (ObjectUtil.isEmpty(purchaseBackPost) || ObjectUtil.isEmpty(purchaseBackPost.getPmdsdocno())) {
            return;
        }
        purchaseBackPost.setPmdssite(Constant.PMDSSITE_AMA);
        String resMessage = soapXmlUtil.getSoapXml("PurchaseBackPost", "pmds_t", purchaseBackPost);
        try {
            //转换为soap消息
            log.info(resMessage);
            //log.info("采购入库单回调：{}",resMessage);
            //发送soap消息，并解析结果
            String result;
            try {
                result = soapXmlUtil.sendSoapMessageNew(resMessage, erpConfig.getUrl());
            } catch (Exception e) {
                result = soapXmlUtil.sendSoapMessageNew(resMessage, erpConfig.URL2);
            }
            XmlResp xmlResp = soapXmlUtil.analysisXml(result);
            log.info("采购仓退返回->{}", JSONObject.toJSONString(xmlResp));
            if (xmlResp.getCode().equals("0")) {
                //更新相应表状态为已下发
                wmsPurchaseMapper.updatePurchaseBackPost(purchaseBackPost.getPmdsdocno(), xmlResp.getData().get("pmdsdocno"), 1);
            } else {
                //更新相应表状态为已下发
                wmsPurchaseMapper.updatePurchaseBackPost(purchaseBackPost.getPmdsdocno(), xmlResp.getData().get("pmdsdocno"), 2);
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}
